package com.twan.kotlinbase.viewstubpresenter

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.*
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.lxj.xpopup.XPopup
import com.skydoves.powerspinner.PowerSpinnerView
import com.twan.kotlinbase.R
import com.twan.kotlinbase.app.BaseDataBindingFragment
import com.twan.kotlinbase.app.Need
import com.twan.kotlinbase.bean.Dict
import com.twan.kotlinbase.bean.ServiceBean
import com.twan.kotlinbase.bean.UploadPic
import com.twan.kotlinbase.databinding.Viewstub1ZhiboBinding
import com.twan.kotlinbase.databinding.Viewstub2ZhiboBinding
import com.twan.kotlinbase.event.TakePhotoEvent
import com.twan.kotlinbase.event.TichengEvent
import com.twan.kotlinbase.network.RxHttpScope
import com.twan.kotlinbase.pop.AddPicPopup
import com.twan.kotlinbase.ui.SendActivity
import com.twan.kotlinbase.ui.TichengRateActivity
import com.twan.kotlinbase.util.*
import com.twan.kotlinbase.widgets.router.Router
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import kotlinx.android.synthetic.main.viewstub2_zhibo.*
import kotlinx.android.synthetic.main.viewstub2_zhibo.btn_ok
import kotlinx.android.synthetic.main.viewstub2_zhibo.chb_privacy
import kotlinx.android.synthetic.main.viewstub2_zhibo.edt_price
import kotlinx.android.synthetic.main.viewstub2_zhibo.spi_zhibo_time
import kotlinx.android.synthetic.main.viewstub2_zhibo.tv_ticheng
import kotlinx.android.synthetic.main.viewstub2_zhibo.rv_multi_pic
import kotlinx.android.synthetic.main.viewstub2_zhibo.rv_multi_video
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.toResponse

//1-需求,2-服务
//发需求:直播
class Zhibo2Presenter: BaseDataBindingFragment<Viewstub2ZhiboBinding>() {
    override fun getLayoutId(): Int {
        return R.layout.viewstub2_zhibo
    }
    lateinit var mLeimu :Dict
    lateinit var mCaiyi :Dict
    lateinit var currImageView:ImageView
    override fun initView(view: View?, savedInstanceState: Bundle?) {
        spi_zhibo_time.text=DateUtils.today()
        initRvMultiPicOrVideo(rv_multi_pic,1)
        initRvMultiPicOrVideo(rv_multi_video,2)
        initRvMultiPicOrVideo(rv_multi_anli,4)

        //时间
        spi_zhibo_time.setOnClickListener {
            SelectDateUtils.initTimePicker(mActivity,spi_zhibo_time).show()
        }
        //类目
        if(SPUtils.getInstance().getString(DictUtils.short_video_type) ==null||SPUtils.getInstance().getString(DictUtils.short_video_type).isEmpty()){
            RxHttpScope().launch {
                var req= RxHttp.get("/dict/findAllByCode").add("dictCode","short_video_type").toResponse<List<Dict>>().await()
                SPUtils.getInstance().put("short_video_type",JsonUtil.objectToJson(req))
                SpiUtils.setSpi(spi_leimu, DictUtils.getDictCache(DictUtils.short_video_type)){ pos,dict ->
                    mLeimu=dict
                }
            }
        }else{
            SpiUtils.setSpi(spi_leimu, DictUtils.getDictCache(DictUtils.short_video_type)){ pos,dict ->
                mLeimu=dict
            }
        }

        if(SPUtils.getInstance().getString(DictUtils.talent_expertise) ==null||SPUtils.getInstance().getString(DictUtils.talent_expertise).isEmpty()){
            RxHttpScope().launch {
                var req= RxHttp.get("/dict/findAllByCode").add("dictCode","talent_expertise").toResponse<List<Dict>>().await()
                SPUtils.getInstance().put("talent_expertise",JsonUtil.objectToJson(req))
                //才艺特长
                SpiUtils.setSpi(spi_caiyi, DictUtils.getDictCache(DictUtils.talent_expertise)){ pos,dict ->
                    mCaiyi=dict
                }
            }
        }else{
            //才艺特长
            SpiUtils.setSpi(spi_caiyi, DictUtils.getDictCache(DictUtils.talent_expertise)){ pos,dict ->
                mCaiyi=dict
            }
        }




        //提成
        tv_ticheng.setOnClickListener {
            Router.newIntent(mActivity).to(TichengRateActivity::class.java).launch()
        }

        btn_ok.setOnClickListener {
            if (uploadPics.size==1 && uploadVideos.size==1) {
                ToastUtils.showShort("请上传主图,二选一")
                return@setOnClickListener
            }
            if (!InputUtils.checkEmpty(edt_liangdian,edt_price)){
                return@setOnClickListener
            }
            if (!InputUtils.checkEmpty(tv_ticheng)){
                return@setOnClickListener
            }
            if (!chb_privacy.isChecked){
                ToastUtils.showShort("请勾选交易规则")
                return@setOnClickListener
            }

            RxHttpScope().launch {
                RxHttp.postJson("service/shopLive/save")
                    .add("caseUrl",getAnliUrl())
                    .add("commissionRate", tv_ticheng.text.toString())
                    .add("goodAtLabel", mLeimu.label)
                    .add("goodAtValue", mLeimu.id)
                    //.add("id", "")
                    .add("imageUrl", getPicsUrl())
                    .add("liveDate", "${spi_zhibo_time.text.toString()} 00:00:00")
                    .add("liveSparkle", edt_liangdian.text.toString())
                    .add("price", edt_price.text.toString())
                    .add("recommendFlag", "0")
                    .add("recommendTime", "")
                    .add("serviceTypeLabel", Need.SHOP_LIVE.title)
                    .add("serviceTypeValue", Need.SHOP_LIVE.desc)
                    .add("talentSkillLabel", mCaiyi.label)
                    .add("talentSkillValue", mCaiyi.id)
                    .add("title", "发布直播服务-"+DateUtils.today2())
                    .add("userId", MyUtils.getLoginInfo()!!.userId)
                    .add("videoUrl", getVideosUrl())
                    .toResponse<Any>().await()
                ToastUtils.showShort("发布直播服务成功")
                mActivity.finish()
            }
        }
    }

    //提成选择
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun dataEvent(event: TichengEvent) {
        tv_ticheng.setTextColor(mActivity.resources.getColor(R.color.text_black))
        tv_ticheng.text=event.rate
    }
    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }


    //图片选择结果处理
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
    }


    //主图只能选择其一
    override fun uploadCallback(url:String){
        if (uploadType == 1){ //选择了图片就清空视频
            //clear(2)
            //rv_multi_video.adapter!!.notifyDataSetChanged()

            uploadPics.add(UploadPic(filepath=url))
            rv_multi_pic.adapter!!.notifyDataSetChanged()
        } else if (uploadType ==2){ //选择了视频就清空图片
            //clear(1)
            //rv_multi_pic.adapter!!.notifyDataSetChanged()

            uploadVideos.add(UploadPic(filepath=url))
            rv_multi_video.adapter!!.notifyDataSetChanged()
        } else if (uploadType ==4) {
            uploadAnlis.add(UploadPic(filepath=url))
            rv_multi_anli.adapter!!.notifyDataSetChanged()
        } else { //单个的图片或者视频
            if (::currImageView.isInitialized){
                currImageView.tag=url
                GlideUtils.load(mActivity,currImageView,url)
            }
        }
    }


}